package com.project.poetry.common.interceptor;

import com.project.poetry.common.constant.ConstantValue;
import com.project.poetry.service.entity.po.user.UserPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 拦截器
 * @author mengxj
 */
@Component
@Slf4j
public class PoetryInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info(String.format("请求路径：%s", uri));
        if(uri.startsWith(ConstantValue.LOGIN_URI)){
            request.setAttribute(ConstantValue.HANDLE_RESPONSE_KEY, ConstantValue.HANDLE_RESPONSE_VALUE);
            return true;
        }
        HttpSession session = request.getSession();
        UserPO user = (UserPO) session.getAttribute(ConstantValue.CUR_USER);
        log.info(String.format("当前人信息：%s", user));
        if(Objects.isNull(user)){
            response.sendRedirect(String.format("%s/page/index", request.getContextPath()));
            return false;
        }else{
            if(ConstantValue.EMPTY_URI.equals(uri)){
                request.getRequestDispatcher("/page/service/index").forward(request, response);
                return false;
            }
            if(!this.checkPreUri(uri)){
                request.setAttribute(ConstantValue.HANDLE_RESPONSE_KEY, ConstantValue.HANDLE_RESPONSE_VALUE);
            }
        }
        return true;
    }

    /**
     * 根据请求uri校验是否需要在请求对象上添加处理控制器结果的标识
     * @param uri 请求uri
     * @see ConstantValue#NOT_HANDLE_RESPONSE_PRE
     * @return 是否需要添加标识
     */
    private boolean checkPreUri(String uri){
        for(String pre : ConstantValue.NOT_HANDLE_RESPONSE_PRE){
            if(uri.startsWith(pre)){
                return true;
            }
        }
        return false;
    }
}
